<?php
/**
 * Created by PhpStorm.
 * User: shiyang
 * Date: 2018/12/17
 * Time: 21:34
 */

namespace App\Http\Controllers\Art;


use App\Http\Controllers\Controller;
use App\Http\Requests\ArticleRequest;
use App\Libraries\DataSource;
use App\Models\Article;
use App\Models\ArticleCategory;
use Illuminate\Support\Facades\Cache;
use Request;
use Response;

class ArticleController extends Controller
{
    public function index()
    {
        $this->authorize('art.article');
        $categories = ArticleCategory::getChains();
        return view('art.article.index', compact('categories'));
    }

    public function table()
    {
        $input = Request::all();
        $offset = Request::get('offset') ? Request::get('offset') : 0;
        $limit = Request::get('limit') ? Request::get('limit') : 20;

        $articles = Article::filter($input)
            ->orderBy('is_top', 'desc')
            ->orderBy('is_hot', 'desc')
            ->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->skip($offset)
            ->limit($limit)
            ->get();
        $total = Article::filter($input)
            ->count();

        $categories = ArticleCategory::getChains();
        $categories = array_prepend($categories, '无', 0);

        $articles->transform(function ($article) use($categories){
            return [
                'id' => $article->id,
                'category_name' => $categories[$article->category_id],
                'title' => $article->title,
                'tags' => $article->tags,
                'author' => $article->author,
                'source' => $article->source,
                'click_count' => $article->click_count,
                'is_top' => $article->is_top,
                'is_hot' => $article->is_hot,
                'is_home' => $article->is_home,
                'state' => $article->state,
                'state_name' => Article::STATES[$article->state],
                'published_at' => $article->published_at,
                'created_at' => empty($article->created_at) ? '' : $article->created_at->format('Y-m-d H:i:s'),
                'updated_at' => empty($article->updated_at) ? '' : $article->updated_at->format('Y-m-d H:i:s'),
            ];
        });

        $ds = new DataSource();
        $ds->rows = $articles;
        $ds->total = $total;

        return Response::json($ds);
    }

    public function show($id)
    {
        $client = new \Predis\Client(null, ['prefix' => '']);
        $client->auth('shiyang');
        $client->set('foo', 'bar2');
        \Log::debug('redis key foo:'.$client->get('foo'));
        $article = Article::find($id);
        return view('art.article.detail', compact('article'));
    }

    public function create()
    {
        $this->authorize('art.article');
        $categories = ArticleCategory::getChains();

        return view('art.article.create', compact('categories'));
    }

    public function store(ArticleRequest $request)
    {
        $this->authorize('art.article');
        $input = $request->all();
        $input['sort'] = time();
        Article::create($input);

        \Session::flash('flash_success', '添加成功');
        return redirect('art/article');
    }

    public function edit($id)
    {
        $this->authorize('art.article');
        $article = Article::find($id);
        if ($article == null) {
            \Session::flash('flash_warning', '无此记录');
            return redirect()->back();
        }
        $categories = ArticleCategory::getChains();
        return view('art.article.edit', compact('article', 'categories'));
    }

    public function update($id, ArticleRequest $request)
    {
        $this->authorize('art.article');
        $input = $request->all();
        $article = Article::find($id);
        $input['content'] = replace_editor_image_url($input['content']);
        $article->update($input);

        \Session::flash('flash_success', '修改成功!');
        return redirect('art/article');
    }

    public function destroy($id)
    {
        $this->authorize('art.article');
        $article = Article::query()->find($id);
        if (! $article) {
            return response()->json([
                'code' => 404,
                'message' => '未找到记录'
            ]);
        }
        $article->state = Article::STATE_DELETED;
        $flag = $article->save();
        $flag && $article->delete();
        if($flag) {
            return response()->json([
                'code' => 200,
                'message' => 'Success'
            ]);
        }
        return response()->json([
            'code' => 500,
            'message' => '服务器异常'
        ]);
    }

    public function updateField($id, $field)
    {
        $this->authorize('art.article');
        if(! in_array($field,['top','hot','home'])){
            return response()->json([
                'code' => 400,
                'message' => '参数有误'
            ]);
        }
        $flag = Article::updateField($id,"is_{$field}");
        if($flag) {
            return response()->json([
                'code' => 200,
                'message' => '操作成功'
            ]);
        }
        return response()->json([
            'code' => 500,
            'message' => '服务器异常'
        ]);
    }

    public function updateState($state)
    {
        $this->authorize('art.article');
        $ids = Request::get('ids');
        if(! array_key_exists($state, Article::STATES)){
            return response()->json([
                'code' => 400,
                'message' => '参数有误'
            ]);
        }
        switch ($state) {
            case Article::STATE_PUBLISHED:
                $stateName = '发布';
                break;
            case Article::STATE_CHECKED:
                $stateName = '审核';
                break;
            case Article::STATE_CANCELED:
                $stateName = '撤回';
                break;
            case Article::STATE_DELETED:
                $stateName = '删除';
                break;
            default:
                $stateName = '操作';
        }
        $flag = Article::updateState($ids, $state);
        if($flag) {
            return response()->json([
                'code' => 200,
                'message' => $stateName . '成功'
            ]);
        }
        return response()->json([
            'code' => 500,
            'message' => '服务器异常'
        ]);
    }

    public function sort()
    {
        $this->authorize('art.article');
        return Article::sort();
    }

    /**
     * 导出excel
     *
     * @return \Illuminate\Http\RedirectResponse|mixed
     */
    public function exportExcel()
    {
        $this->authorize('art.article');
        $input = Request::all();
        $offset = 0;
        $limit = 50000;//最多导出5万条数据
        $articles = Article::filter($input)
            ->orderBy('is_top', 'desc')
            ->orderBy('is_hot', 'desc')
            ->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->skip($offset)
            ->limit($limit)
            ->get();

        if ($articles->isEmpty()) {
            \Session::flash('flash_warning', '暂无有效记录，导出excel失败');
            return redirect()->back()->withInput($input);
        }

        $categories = ArticleCategory::getChains();
        $categories = array_prepend($categories, '无', 0);

        $articles->transform(function ($article) use($categories){
            return [
                'id' => $article->id,
                'category_name' => $categories[$article->category_id],
                'title' => $article->title,
                'tags' => $article->tags,
                'author' => $article->author,
                'source' => $article->source,
                'click_count' => $article->click_count,
                'is_top' => $article->is_top,
                'is_hot' => $article->is_hot,
                'is_home' => $article->is_home,
                'state' => Article::STATES[$article->state],
                'published_at' => $article->published_at,
                'created_at' => empty($article->created_at) ? '' : $article->created_at->format('Y-m-d H:i:s'),
                'updated_at' => empty($article->updated_at) ? '' : $article->updated_at->format('Y-m-d H:i:s'),
            ];
        });
        $articles = $articles->toArray();

        $firstRow = array_keys($articles[0]);
        $rows = array_prepend($articles, $firstRow);
        $fileName = sprintf("article-export-%s", date('YmdHis'));
        return download_excel($fileName, $rows);
    }



}
